package com.example.as_sum.application;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.example.as_sum.R;
import com.example.as_sum.util.toast.ToastUtil;

/**
 * Created by ran on 2016/11/23.
 */

public class DownService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("---DownService---","-----onCreate");
    }
    NotificationCompat.Builder mBuilder;
    NotificationManager mManager;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("---DownService---","-----onStartCommand");

        Toast.makeText(this,"开始下载",Toast.LENGTH_LONG).show();
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Uri uri = Uri.parse("www.baidu.com");
        Intent it = new Intent(Intent.ACTION_VIEW, uri);
        PendingIntent mIntent=PendingIntent.getActivity(this,0,it,PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("开始下载");
        mBuilder.setContentText("点击下载");
        mBuilder.setSmallIcon(R.drawable.logo);
        mBuilder.setContentIntent(mIntent);
        mBuilder.setAutoCancel(true);
        mBuilder.setOngoing(true);

        new Thread(new Runnable() {
            @Override
            public void run() {

                for (int x=0;x<20;x++){
                    mBuilder.setContentText("正在下载");
                    mBuilder.setProgress(100,x*5,false);
                    mManager.notify(1000,mBuilder.build());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                mBuilder.setContentText("下载完成").setProgress(0, 0, false);
                mManager.notify(1000,mBuilder.build());
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        Log.e("---DownService---","-----onDestroy");
        super.onDestroy();
    }
}
